const { JJCourse, JJCourseCamp, JJCourseImages, JJUserCourseSettle, JJUserCourse, Ctcdb, JJCourseSettleOrder, JJCourseAccount,
  JJCourseUserConfirm } = require('../../models/ctcdb');
const _ = require('lodash');
const moment = require('moment');
const BaseResp = require('../../utils/baseResp');
const errorCode = require('../../utils/errorCode');
const tools = require('../../utils/tools');

async function queryCourseOtherInfo(ids, { isImage, isCourse }) {
  const [images, courseList] = await Promise.all([
    function() {
      if (isImage) {
        return JJCourseImages.findAll({
          where: {
            courseId: ids
          },
          attributes: ['courseId', 'imagePath'],
          raw: true
        })
      }
      return [];
    }(),
    function() {
      if (isCourse) {
        return JJCourse.findAll({
          where: {
            id: ids
          },
          attributes: ['type', 'id', 'courseName', 'classNum', 'startTime', 'classTime',
            'totalMoney', 'peopleNum', 'label', 'storeName', 'description', 'JUserId'],
          raw: true
        })
      }
      return [];
    }(),
  ]);
  const courseMap = {};
  courseList.forEach((item) => {
    if (!courseMap[item.id]) {
      item.startTime = tools.formatHHMM(item.startTime);
      courseMap[item.id] = item;
    }
  });
  const imageMap = _.groupBy(images, 'courseId');
  return {
    imageMap,
    courseMap
  }
}

async function createUserConfirm({ userIds, courseId, lUserId, transaction, totalSum }) {
  const arr = [];
  userIds.forEach((item) => {
    arr.push({
      status: 0,
      jUserId: item,
      lUserId,
      courseId
    })
  });
  await JJCourseUserConfirm.bulkCreate(arr, { transaction });
  await JJCourseSettleOrder.create({
    courseId,
    lUserId,
    totalSum,
    status: 0
  }, {
    transaction
  })
}

/**
 * 团课逍客
 * @param users 销课的人员
 * @param courseId 课程Id
 * @param lUserId 教练Id
 * @param description 描述
 * @param images 记录的图片信息
 * @returns {Promise<void>}
 */
async function courseTuanSellte({ users, courseId, lUserId, description, images }) {
  const joinUsers = await JJUserCourse.findAll({
    where: {
      state: 1,
      type: 1,
      courseId
    },
    attributes: ['jUserId'],
    raw: true
  });
  const userIds = [];
  joinUsers.forEach((item) => {
    userIds.push(item.jUserId);
  });
  const courseAccount = await JJCourseAccount.findOne({
    where: {
      courseId
    },
    attributes: ['balance'],
    raw: true
  });
  if (!courseAccount) {
    throw BaseResp.error(errorCode.COURSE.COURSE_ACCOUNT_ERROR)
  }
  const totalSum = courseAccount.balance || 0;
  const transaction = await Ctcdb.transaction();
  try {
    if (users.length > 0) {
      // 参加过课的人
      await JJUserCourse.update({
        isJoin: 1
      }, {
        where: {
          courseId,
          jUserId: users,
          state: 1
        },
        transaction
      })
    }
    // 暂时不考虑销课之前的状态了（统一全部销课）
    await JJUserCourse.update({
      status: 10
    }, {
      where: {
        courseId,
        state: 1
      },
      transaction
    });
    // 创建销课信息
    await JJUserCourseSettle.create({
      courseId,
      type: 1,
      lUserId,
      images: images && JSON.stringify(images) || '[]',
      description
    }, {
      transaction
    });
    // 主课程销课
    await JJCourse.update({
      cStatus: 10
    }, {
      where: {
        id: courseId
      },
      transaction
    });
    await createUserConfirm({ userIds, lUserId, courseId, transaction, totalSum });
    await transaction.commit();
  } catch (e) {
    if (e) {
      await transaction.rollback()
    }
    return Promise.reject(e)
  }
}

async function courseSiSettle({ campId, courseId, images, users, description, lUserId }) {
  const courseCamp = await JJCourseCamp.findOne({
    where: {
      courseId,
      id: campId
    },
    attributes: ['cStatus'],
    raw: true
  });
  if (!courseCamp) {
    throw BaseResp.error(errorCode.COURSE.NOT_CLASS)
  }
  const { cStatus } = courseCamp;
  if (cStatus === 10) {
    throw BaseResp.error(errorCode.COURSE.HAS_END_COURSE_CLASS)
  }
  let count = 0;
  let isLastClass = false;
  let totalSum = 0;
  // 查询是否是最后一节课时_
  count = await JJCourseCamp.count({
    where: {
      courseId,
      cStatus: 1
    },
  });
  if (count === 1) {
    isLastClass = true;
    const courseAccount = await JJCourseAccount.findOne({
      where: {
        courseId
      },
      attributes: ['balance'],
      raw: true
    });
    if (!courseAccount) {
      throw BaseResp.error(errorCode.COURSE.COURSE_ACCOUNT_ERROR)
    }
    totalSum = courseAccount.balance;
  }
  const joinUsers = await JJUserCourse.findAll({
    where: {
      type: 1,
      state: 1,
      courseId
    },
    attributes: ['jUserId'],
    raw: true
  });
  const userIds = [];
  joinUsers.forEach((item) => {
    userIds.push(item.jUserId);
  });
  const transaction = await Ctcdb.transaction();
  try {
    // 说明课时可以进销课
    if (users) {
      await JJUserCourse.update({
        isJoin: 1
      }, {
        where: {
          courseId,
          campId,
          jUserId: users,
          state: 1
        },
        transaction
      })
    }
    // 销课所有的
    await JJUserCourse.update({
      status: 10
    }, {
      where: {
        courseId,
        campId,
        state: 1
      },
      transaction
    });
    //  主课时销课
    await JJCourseCamp.update({
      cStatus: 10
    }, {
      where: {
        id: campId
      },
      transaction
    });
    // 创建课时销课信息
    await JJUserCourseSettle.create({
      campId,
      courseId,
      type: 2,
      lUserId,
      images: images && JSON.stringify(images) || '[]',
      description
    }, {
      transaction
    });
    // 如果是最后一节课时(说明最后的销课,主课程直接进行销课)
    if (isLastClass) {
      await JJCourse.update({
        cStatus: 10
      }, {
        where: {
          id: courseId
        },
        transaction
      });
      await createUserConfirm({ userIds, courseId, lUserId, transaction, totalSum });
    }
    await transaction.commit();
  } catch (e) {
    if (transaction) {
      await transaction.rollback()
    }
    return Promise.reject(e)
  }
}

module.exports = {
  // 查询课程的一些其他信息聚合
  queryCourseOtherInfo,
  // 团课销课
  courseTuanSellte,
  // 私教销课
  courseSiSettle
};
